package com.imclient.server;

import java.io.ByteArrayOutputStream;
import java.io.OutputStream;

import com.imclient.message.Header;
import com.imclient.message.Message;

public class SendServer {

	private OutputStream opt;

	public SendServer(OutputStream opt) {
		this.opt = opt;

	}

	public boolean sendMessage(Message message) {
		if (opt != null) {
			try {
				
				System.out.println(new String(MessageToBytes(message)));
				
				opt.write(MessageToBytes(message));
				opt.flush();
				return true;
			} catch (Exception e) {
				e.printStackTrace();
			}finally{}
		}
		return false;
	}

	private byte[] MessageToBytes(Message msg) throws Exception {

		if(msg.getBody()==null){
			msg.setBody(new byte[0]);
		}
		ByteArrayOutputStream bsa = new ByteArrayOutputStream();

		
		Header[] headers = msg.getHeaders();
		for (Header h : headers) {
			bsa.write((h.getKey() + ":" + h.getValue() + "\r\n").getBytes());
		}
		bsa.write(("Length:" + msg.getBody().length + "\r\n").getBytes());
		bsa.write("\r\n".getBytes());
		if (msg.getBody().length > 0) {
			bsa.write(msg.getBody());
		}
		bsa.write(new byte[]{'-','\r','\n','-'});
		return bsa.toByteArray();
	}

}
